/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sUtils;


import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

/**
 *
 * @author thomas.s
 */
public class TextInput extends Canvas {

    MIDlet parent=null;
    int caps=0,pos=0,len=0, max=1024;
    int ox,oy, th=20; long ot;
    char c[] = new char[max];
    int cx[] = new int[max];
    int cy[] = new int[max];
    Keypad pad = new Keypad();

    
    public TextInput( MIDlet md, String text )
    {
        parent = md;
        pos=len=text==null ? 0 : text.length();
        if (len>0) for ( int i=0; i<len; i++ ) c[i]=text.charAt(i);
    }


    public void paint(Graphics g)
    {
        int w = getWidth();
        int h = getHeight();
        Font f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_LARGE);
        th = f.getHeight();
        int tw;
        g.setFont( f );
        g.setColor( 0x0 );
        g.fillRect( 0,0,w,h );
       
        g.setColor(0xf0f0f0);
        int x = 0, y = 0; String s;
        for ( int i=0; i<max; i++ )
        {
            if (pos==i) g.drawRect(x+1, y, 1,th);
            if (i<len) {
                s = ""+c[i];

                tw=f.stringWidth(s);
                if (tw+x>=w) { y+=th; x=0; }
                g.drawString(s, x, y, 0); x+=tw;
                cx[i]=x; cy[i]=y;
            }

        }
        pad.paint(g, caps);
    }

    public void onKey( String s )
    {
        if (s!=null)
        {
        if (parent!=null) Display.getDisplay(parent).vibrate(5);
        if (s.equals("Space")) { c[pos]=' '; pos++; } else
        if (s.equals("Cap")) { caps = caps==0 ? 1 : 0; } else
        if (s.equals("<")) { if (pos>0) pos--; } else
        if (s.equals(">")) { if (pos<len) pos++; } else
        if (s.equals("Del"))
        {
            //if (pos==len && pos>0) { pos--; len=pos; c[pos]=' '; } else
            for ( int i=pos-1; i<len; i++ ) if (i>0) c[i]=c[i+1]; c[len]=0; 
            if (pos>0) pos--; if (len>0) len--; 


        } else
        {
            if (len<max) for ( int i=len; i>pos; i-- ) c[i]=c[i-1]; len++;
            c[pos]=s.charAt(caps); pos++; caps=1;
        }
        if (pos>len) len=pos;
        repaint();
        }
    }

    public void pointerPressed( int x, int y )
    {
        int j=-1;
        for ( int i=0; i<len; i++ )
        {
            if (y>=cy[i] && y<(cy[i]+th))
            {
                if (x>=cx[i]) j=i;
            }
        }
        if (j!=pos && j>=0) { pos=j; repaint(); }
        onKey( pad.hitTest(x, y) );
    }

    public void pointerReleased( int x, int y )
    {
        ot = System.currentTimeMillis();
    }

    public String getString()
    {
        String erg = "";
        for ( int i=0; i<len; i++ ) erg = erg + c[i];
        return erg;
    }



}
